import 'dart:convert';
import 'dart:math';

import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';
import 'package:chathouse/public/Config.dart';
import 'package:image_picker/image_picker.dart';
import '../../../model/wallet_cel.dart';
import '../../../widgets/base_appbar.dart';
import '../../base/base.dart';
import '../expert_root_page.dart';
import '../service_list_page.dart';

// ignore: must_be_immutable
class WalletCerFeedbackDetail extends BaseStatefulWidget {
  int type;
  String cerId;
  String version;
  WalletCerFeedbackDetail(this.type,this.cerId,this.version, {Key? key}) : super(key: key);

  @override
  _WalletCerFeedbackDetailState createState() =>
      // ignore: no_logic_in_create_state
      _WalletCerFeedbackDetailState(type,cerId, version);
}

class _WalletCerFeedbackDetailState
    extends BaseStatefulWidgetState<WalletCerFeedbackDetail> {
  int feebackType = 0;
  String feebackTypeCerId;
  String feebackversion;

  _WalletCerFeedbackDetailState(this.feebackType,this.feebackTypeCerId,this.feebackversion);

  String text = "";
  TextEditingController controller = TextEditingController();

  List<String> imageUrls = [];
  Function(List<String> imageUrls)? onSelectImage;
  int maxLength = 6;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      updateState(LoadState.success);
    });
  }

  List<Widget> getSubWidgets() {
    List<Widget> subWidgets = [];
    for (var element in imageUrls) {
      subWidgets.add(getImageWidget(element));
    }
    if (imageUrls.length < 6) {
      subWidgets.add(getAddWidget());
    }

    return subWidgets;
  }

  Widget getImageWidget(String url) {
    double itemW = (1.sw - 26.w * 2 - 16.w * 2) / 3.0 - 0.1;
    return ClipRRect(
      child: Container(
        width: itemW,
        height: itemW,
        decoration: BoxDecoration(
            color: MyColors.gary_230230230,
            borderRadius: BorderRadius.circular(20.w)),
        child: ImageUtils.image(url,
            imageType: ImageType.NETWORK,
            width: itemW,
            height: itemW,
            key: UniqueKey()),
      ),
      borderRadius: BorderRadius.circular(20.w),
    );
  }

  Widget getAddWidget() {
    double itemW = (1.sw - 26.w * 2 - 16.w * 2) / 3.0 - 0.1;
    return Container(
      width: itemW,
      height: itemW,
      decoration: BoxDecoration(
          color: MyColors.gary_230230230,
          borderRadius: BorderRadius.circular(20.w)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ImageUtils.image(Res.image_pick_add, width: 51.w, height: 51.w),
          SizedBox(height: 6.w),
          Text(
            "選擇照片",
            style: getTextStyle(16.sp, color: MyColors.brow_25511377),
          ),
        ],
      ),
    ).setOnClickListener(() {
      onAddImage();
    });
  }

  toFeedback() {
    var map = {
      "feedbackDes": controller.text ?? "",
      "feedbackImg": imageUrls.join(','),
      "feedbackType": "$feebackType",
      "id":feebackTypeCerId,
      "version":feebackversion
    };
    Apis.cerApprovalRecharge(map)
        .then((value) {
          ToastUtil.showToast('反饋成功');
          Get.back();
          Get.back();
          Get.back();
    })
        .onError((error, stackTrace) {});
  }

  void onAddImage() async {
    int type = await Get.bottomSheet(Container(
      width: 1.sw,
      height: 120.w,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w))),
      child: Column(
        children: [
          Text(
            "從相冊中選取",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
                  width: double.infinity,
                  height: 60.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                              width: 1.0.w, color: MyColors.gary_149149149))))
              .setOnClickListener(() {
            Get.back(result: 1);
          }),
        ],
      ),
    ));
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
        source: type == 1 ? ImageSource.gallery : ImageSource.camera);
    var imgData = await image?.readAsBytes();
    if(imgData != null) {
      Obj.showLoading();
    }
    Map result;
    String? url;
    Apis.uploadFile(imgData!, image?.name ?? "image.png")
        .then((response) => {
              Obj.dismissLoading(),
              debugPrint("upload=${response?.data.toString()}"),
              result = jsonDecode(response?.data ?? ""),
              url = result["url"],
              if (url != null)
                {
                  setState(() {
                    imageUrls.add(url!);
                  }),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  @override
  Widget viewPageBody() {
    // TODO: implement viewPageBody
    return Scaffold(
      appBar: getAppBar(title: "驗證未通過"),
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 24.w),
          child: ListView(
            children: [
              Text(
                "内容描述",
                style: getTextStyle(24.sp,
                    color: Colors.black, fontType: FontType.BOLD),
              ),
              SizedBox(
                height: 16.w,
              ),
              Container(
                height: 156.w,
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10.w),
                  border: Border.all(color: Styles.c_999, width: 1.w),
                ),
                child: TextField(
                  controller: controller,
                  style: getTextStyle(16.sp, color: Colors.black),
                  onChanged: (val) {
                    text = val;
                    setState(() {});
                  },
                  decoration: InputDecoration(
                    hintText: "請說明想要反饋的内容",
                    hintStyle: getTextStyle(16.sp, color: Styles.c_999),
                    border: InputBorder.none,
                  ),
                ),
              ),
              SizedBox(
                height: 42.w,
              ),
              Text(
                "上傳圖片(提供相關截圖)",
                style: getTextStyle(24.sp,
                    color: Colors.black, fontType: FontType.BOLD),
              ),
              SizedBox(
                height: 4.w,
              ),
              Text(
                "最多8張圖片",
                style: getTextStyle(20.sp,
                    color: Styles.c_999, fontType: FontType.BOLD),
              ),
              SizedBox(
                height: 16.w,
              ),
              Wrap(
                spacing: 16.w,
                runSpacing: 16.w,
                children: getSubWidgets(),
              ),
              SizedBox(
                height: 70.w,
              ),
              InkWell(
                onTap: () {
                  toFeedback();
                },
                child: Container(
                  alignment: Alignment.center,
                  child: SizedBox(
                    width: 200.w,
                    height: 41.w,
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: Styles.mainColor,
                          borderRadius: BorderRadius.circular(Styles.magin_16)),
                      child: Text(
                        "提交",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 22.w,
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
